import 'package:flutter/material.dart';
import 'package:flutter_aliplayer/flutter_aliplayer.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/controller/live/qkd_player_logic.dart';
import 'package:sports_new/utils/routes.dart';
import 'package:sports_new/view/overlay/live_float_widget.dart';
import 'package:visibility_detector/visibility_detector.dart';

class QkdPlayer extends StatefulWidget {
  const QkdPlayer({super.key, required this.logic});

  final QkdPlayerLogic logic;

  @override
  State<QkdPlayer> createState() => _QkdPlayerState();
}

class _QkdPlayerState extends State<QkdPlayer> {

  @override
  void didChangeDependencies() {
    widget.logic.addListener(() {
      try {
        if (mounted) {
          setState(() {});
        }
      }catch(e){
        Logger().d(e);
      }
    });
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return VisibilityDetector(
      key: ValueKey(widget.logic.url),
      onVisibilityChanged: (VisibilityInfo info) async{
        if(info.visibleBounds.isEmpty){
          try {
            widget.logic.setMute(true);
          }catch(e){
            Logger().d(e);
          }
          List<String> livePage = [
            Routes.liveNormal,Routes.zqMatchDetail,Routes.lqMatchDetail
          ];
          if(widget.logic.status == PlayStatus.started && livePage.every((element) => !Get.currentRoute.contains(element))) {
            LiveFloatController.instance.show();
          }
        }else{
          widget.logic.setMute(false);
          await LiveFloatController.instance.off();
        }
      },
      child: Align(
        alignment: Alignment.center,
        child: Container(
          color: Colors.black,
          width: widget.logic.width,
          height: widget.logic.height,
          child: AliPlayerView(
            onCreated: (viewId) => widget.logic.setPlayerView(viewId),
            x: 0, y: 0,
            width: widget.logic.width,
            height: widget.logic.height,
            aliPlayerViewType: AliPlayerViewTypeForAndroid.textureview,
          ),
        ),
      ),
    );
  }
}
